/*
** video_client.c -- a stream socket video client
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
        if (sa->sa_family == AF_INET) {
                return &(((struct sockaddr_in*)sa)->sin_addr);
        }

        return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

typedef struct video_client_t {
	int sockfd;
} video_client_t;

void video_client(struct video_client_t *client, char* server_address, char* port)
{
	struct addrinfo hints, *servinfo, *p;
	int numbytes;
        int rv;
        char s[INET_ADDRSTRLEN];
	//video_client_t *client;

	memset(&hints, 0, sizeof hints);
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;

        if ((rv = getaddrinfo(server_address, port, &hints, &servinfo)) != 0) {
                fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
                exit(1);
        }

        // loop through all the results and connect to the first we can
        for(p = servinfo; p != NULL; p = p->ai_next) {
                if ((client->sockfd = socket(p->ai_family, p->ai_socktype,
                                p->ai_protocol)) == -1) {
                        perror("client: socket");
                        continue;
                }

                if (connect(client->sockfd, p->ai_addr, p->ai_addrlen) == -1) {
                        close(client->sockfd);
                        perror("client: connect");
                        continue;
                }

                break;
        }

        if (p == NULL) {
                fprintf(stderr, "client: failed to connect\n");
                exit(1);
        }

        inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
                        s, sizeof s);
        printf("client: connecting to %s\n", s);

        freeaddrinfo(servinfo); // all done with this structure

	//return client;
}

int send_video_data(video_client_t *client, char* buf, int length)
{
	int sent = 0;
	int rc;

	while (sent < length) {
		if ((rc = send(client->sockfd, buf + sent, length - sent, 0)) == -1) {
                	perror("failed sending data to server");
                	exit(1);
        	}
		sent += rc;
	}
	
	return 0;
}

int close_video_client(video_client_t *client)
{
	close(client->sockfd);
}
